<?php
if (!defined("__WD__")) exit("Wrong Connect");

class Obj {

	public $name;
	
	public $type = 1; // 0 : String, 1 : Obj

	public $attr = array();
	
	public $node = array();
	
	public function __construct( $name, $type = 1 ) {
		$this->name = $name;
		$this->type = $type;
	}
	
	public function __toString() {
		
		$single_tags = array( "link", "br", "hr", "img", "input" );
		$single_attr = array( "required" );
		
		$ret = "";
		if ( $this->type == 0 ) {
			$ret .= $this->name;
		}
		else if ( in_array($this->name, $single_tags) ) {
			$ret .= "<{$this->name}";
			foreach($this->attr as $key => $value) $ret .= " ".$key."=\"".htmlspecialchars($value)."\"";
			$ret .= " />";
		}
		else {
			$ret .= "<{$this->name}";
			foreach($this->attr as $key => $value) $ret .= " ".$key."=\"".htmlspecialchars($value)."\"";
			$ret .= ">";
			foreach($this->node as $value) {
				if ($value instanceof ObjItem) $ret .= $value->__toString();
				else $ret .= $value;
			}
			$ret .= "</{$this->name}>";
		}
		return $ret;
	}
	
	public function attr( $name, $value = null ) {
		if ( is_array($name) ) {
			$this->attr = array_merge($this->attr, $name);
		}
		else if ($value === null) {
			return $this->attr[$name];
		}
		else {
			$this->attr[$name] = $value;
		}
		return $this;
	}

	public function removeAttr( $name ) {
		unset($this->attr[$name]);
		return $this;
	}

	public function addClass( $name ) {
		if ( isset($this->attr["class"]) ) {
			$classes = explode(" ", $this->attr["class"]);
			array_push($classes, $name);
			$this->attr["class"] = implode(" ", $classes);
		}
		else {
			$this->attr["class"] = $name;
		}
		return $this;
	}
	
	public function removeClass( $name ) {
		if ( isset($this->attr["class"]) ) {
			$classes = explode(" ", $this->attr["class"]);
			$key = array_search($name, $classes);
			if ( ($key = array_search($name, $classes)) !== false ) {
				array_splice($classes, $key, 1);
				$this->attr["class"] = implode(" ", $classes);
			}
		}
		return $this;
	}
	
	public function append( $obj ) {
		if ($obj instanceof Obj)
			array_push($this->node, $obj);
		else 
			array_push($this->node, new Obj($obj, 0));
		return $this;
	}
	public function prepend( $obj ) {
		if ($obj instanceof Obj)
			array_unshift($this->node, $obj);
		else 
			array_unshift($this->node, new Obj($obj, 0));
		return $this;
	}
	public function first( $n = 0 ) {
		if ( $n >= count($this->node) ) throw new Error("?!");
		return $this->node[$n];
	}
	public function last( $n = 0 ) {
		$len = count($this->node);
		if ( $n >= $len ) throw new Error("?!");
		return $this->node[$len - $n - 1];
	}
/*	public function text() {
		
		
	}
*/
}